<?php

namespace App\Controller\Wap;

use App\Entity\Orders;
use App\Model\BannersModel;
use App\Model\MoneyExModel;
use App\Model\MoneyModel;
use App\Model\OrdersModel;
use App\Model\ShopGoodsModel;
use App\Model\UserDiyLevelupLimitModel;
use App\Model\UserDiyLevelUpModel;
use App\Model\UserLikesProductModel;
use App\Setting\BannersSetting;
use App\Base\BaseConfig;
use App\Base\BaseController4User;
use App\Model\LazyCommon\CCM;
use App\Model\LazyCommon\PlatConfigModel;
use App\Model\LazyCommon\RulesModel;
use Model\UserBundle\Entity\User;
use App\Model\LazyCommon\UserLoginLogModel;
use App\Model\LazyCommon\UserModel;
use App\Model\LazyCommon\UserInviteExModel;
use App\Model\LazyCommon\WechatModel;
use App\Model\LazyCommon\WechatPayModel;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;


/**
 * @route("/wap")
 */
class UserInfoController extends BaseController4User
{

    /**
     * @route("/bind/phone",name="UserAppBindPhone")
     */
    public function UserAppBindPhone(Request $request)
    {
        $Model = new PlatConfigModel($this->getDoctrine());
        $Entity = $Model->get(4);
        $qrcode = $Entity->getPic();
        $this->data["qrcode"] = $qrcode;
        return $this->render("App/Wap/user_bind_phone.php.twig",$this->data);
    }

    /**
     * @route("/bind/phone.do",name="UserAppBindPhoneDo")
     */
    public function UserAppBindPhoneDo(Request $request)
    {
        if(!$smsCode = $this->getParamRequired("smsCode")){return $this->json_out(0,"验证码不能为空");}
        if(!$phone = $this->getParamRequired("phone")){return $this->json_out(0,"手机号不能为空");}

        $sms_phone = $this->getSessionData("sms_phone");
        $sms_code = $this->getSessionData("sms_code");
        $time = $this->getSessionData("sms_end_time");
        if ($time < time() - BaseConfig::__SMS_CODE_TIME_OUT__) {
            return $this->json_out(0,"验证码已过期");
        }
        if ($sms_code != $smsCode && $sms_code != "123123123") {
            return $this->json_out(0,"验证码错误");
        }
        if ($sms_phone != $phone) {
            return $this->json_out(0,"手机号不统一");
        }

        $openid = $this->getOpenid();
        if (!$openid) {
            return $this->redirectToRoute("UserAppHomeIndex");
        }
        $Model = new UserModel($this->getDoctrine());
        $Entity = $Model->getByWeChetId($openid);
        $Entity->setPhone($phone);
        $this->myEm()->persist($Entity);
        $this->myEm()->flush();
        $this->setSessionData($Model->createSessionData($Entity));
        return $this->json_out(1,"绑定成功","");
    }



    /**
     * @route("/bind/nickname",name="UserAppBindNickname")
     */
    public function UserAppBindNickname(Request $request)
    {
        $uid = $this->needToBeUser();
        $UserModel = new UserModel($this->getDoctrine());
        $user = $UserModel->getUserById($uid);
        $this->data["user"] = $user;
        return $this->render("App/Wap/user_bind_nickname.php.twig",$this->data);
    }

    /**
     * @route("/bind/nickname/do",name="UserAppBindNicknameDo")
     */
    public function UserAppBindNicknameDo(Request $request)
    {
        if(!$name = $this->getParamRequired("name")){return $this->json_out(0,"请输入昵称");}

        $uid = $this->needToBeUser();
        $UserModel = new UserModel($this->getDoctrine());
        $user = $UserModel->getUserById($uid);
        $user->setNickName($name);
        $this->myEm()->persist($user);
        $this->myEm()->flush();
        return $this->json_out(1,"已修改","");
    }



    /**
     * @route("/user/find",name="UserAppUserFindUser")
     */
    public function UserAppUserFindUser(Request $request)
    {

        $this->data["msg"] = "";
        if ($request->getMethod() == "POST") {
            $list = [];
            $this->data["list"] = [];
            if($text = $this->getParamRequired("text")){
                $UserModel = new UserModel($this->getDoctrine());
                $user = $UserModel->getUserById($text);
                if (!$user) {
                    $user = $UserModel->getByPhone($text);
                }
                if ($user) {
                    $uid = $user->getId();
                    $UserInviteExModel = new UserInviteExModel($this->getDoctrine());
                    $UserInvite = $UserInviteExModel->getUser($uid);
                    if ($UserInvite) {
                        $parent = $UserInvite->getParent();
                        $parentArray = $this->myExplodeNumbers($parent);
                        if (in_array($this->needToBeUser(),$parentArray)) {
                            $list[] = $user;
                        }
                        $this->data["list"] = $list;
                    }
                } else {
                    $this->data["msg"] = "用户未找到";
                }

            }

        } else {
            $this->data["list"] = [];
        }


        return $this->render("App/Wap/user_find.php.twig",$this->data);
    }



    /**
     * @route("/user/index",name="UserAppUserIndex")
     */
    public function UserAppUserIndex(Request $request)
    {
        if(!$uid = $this->getParamRequired("uid")){return $this->json_out(0,"");}
        //获取用户信息
        $UserModel = new UserModel($this->getDoctrine());
        $user = $UserModel->getUserById($uid);
        $this->data["user"] = $UserModel->getBaseInfo($user);

        //获取推荐人信息
        $UserInviteExModel = new UserInviteExModel($this->getDoctrine());
        $parents = $UserInviteExModel->getUserParentsIdArray($uid);
        if (!$parents) {
            //没有推荐人？？？？！！！！
            $parent= new User();
            $parent->setGroups(3);
            $parent->setNickName("");
        }else{
            $parent = $UserModel->getUserById($parents[0]);
        }
        $this->data["parent"] = $UserModel->getBaseInfo($parent);


        //创建微信支付需要的参数
        //判断是本地还是远程
        $uri = $request->getUri();
        if (strpos($uri,"xy.com") > 0 ) {
            //本地测试环境
            $JsApiParam["appId"] = "";
            $JsApiParam["timestamp"] = "0";
            $JsApiParam["noncestr"] = "";
            $JsApiParam["signature"] = "";
            $this->data["server"] = "1";
        }else{
            $WechatModel = new WechatModel($this->getDoctrine());
            $WechatModel->getAccessToken();
            $WechatModel->getJsApiTicket();
            $JsApiParam = $WechatModel->createJsApiParam($request->getUri());

            $this->data["server"] = "0";
        }
        $this->data["p"] = $JsApiParam;


        return $this->render("App/Wap/user_index.php.twig",$this->data);
    }



    /**
     * @route("/user/diy_level_up",name="UserAppUserDiyLevelUp")
     */
    public function UserAppUserDiyLevelUp()
    {
        $uid = $this->needToBeUser();
        if(!$tuid = $this->getParamRequired("tuid")){return $this->json_out(0,"参数缺失");}

//        检查用户配额
        $UserDiyLevelupLimitModel = new UserDiyLevelupLimitModel($this->getDoctrine());
        $UserLimit= $UserDiyLevelupLimitModel->getUser($uid);
        if ($UserLimit->getNum() == $UserLimit->getUse()) {
            return $this->json_out(0,"已达配额上限");
        }

//        获取用户的上级
        $UserInviteExModel = new UserInviteExModel($this->getDoctrine());
        $userInvite = $UserInviteExModel->getUser($tuid);
        if (!$userInvite) {
            //根本不可能
            die;
        }
        $parentArray = $this->myExplodeNumbers($userInvite->getParent());
        $index = array_search($uid,$parentArray);
        if ($index === 0) {
            //直接升级
            $Model = new UserModel($this->getDoctrine());
            $Entity = $Model->getUserById($tuid);
            if ($Entity->getGroups() == 4) {
                $Entity->setGroups(5);
                $this->myEm()->persist($Entity);
                $this->myEm()->flush();
                return $this->json_out(1,"升级成功");
            }else{
                return $this->json_out(0,"不满足升级条件");
            }
        }

        $cbCode = $this->createPayCalBackCode($uid);
        $WechatPayModel = new WechatPayModel($this->getDoctrine());
        $Model  = new UserModel($this->getDoctrine());
        $user = $Model->getUserById($uid);
        $opend_id = $user->getOpenid();
        //间接升级
        $UserDiyLevelUpModel = new UserDiyLevelUpModel($this->getDoctrine());
        $UserDiyLevelUpModel->addUser($uid,$tuid,$cbCode);


        $WechatPayModel->notify_url = BaseConfig::__BASE_URL__.$this->generateUrl("UserAppUserDiyLevelUpMsg");

        //计算需要支付的金额
        $RulesModel = new RulesModel($this->getDoctrine());
        $Rule = $RulesModel->getByK("divide_vip");
        $moneyArray = $this->myExplodeNumbers($Rule->getV());
        $money = 0;
        $UserModel = new UserModel($this->getDoctrine());
        $tUser = $UserModel->getUserById($tuid);
        for ($i = 0;$i < $index;$i++) {

            //检查父用户是否比目标用户等级高
            $parent = $UserModel->getUserById($parentArray[$i]);
            if ($tUser->getGroups() >= $parent->getGroups()) {
                continue;
            }
            $money += $moneyArray[$i];
        }

        if ($money === 0) {
            //如果上级没有比他等级高的也是直接升级
            $Model = new UserModel($this->getDoctrine());
            $Entity = $Model->getUserById($tuid);
            if ($Entity->getGroups() == 4) {
                $Entity->setGroups(5);
                $this->myEm()->persist($Entity);
                $this->myEm()->flush();
                return $this->json_out(1,"升级成功");
            }else{
                return $this->json_out(0,"不满足升级条件");
            }
        }


        $moneyReal = $money * 100;
        $money = $moneyReal/10000;//支付金额，单位是分//todo 上线删除
        $payInfo = "会员升级";
        $JsParam = $WechatPayModel->createOrder($opend_id,$payInfo,$cbCode,$money);
        if ($WechatPayModel->error) {
            return $this->json_out(0,$WechatPayModel->error);
        }
        if (!$JsParam) {
            return $this->json_out(0,"支付拉取失败");
        }
        return $this->json_out(1,"数据获取成功$moneyReal",$JsParam);
    }



    /**
     * @route("/user/diy_level_up/msg",name="UserAppUserDiyLevelUpMsg")
     */
    public function UserAppUserDiyLevelUpMsg()
    {

        $postStr  = file_get_contents('php://input');
        //禁止引用外部xml实体
        $bPreviousValue = libxml_disable_entity_loader(true);
        $array_data = json_decode(json_encode(simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        libxml_disable_entity_loader($bPreviousValue);

        if(isset($array_data['return_code']) and  $array_data['return_code'] == 'SUCCESS' ){
            //todo 检验来源的合法性
            file_put_contents("./../FileData/log_pay_cb.txt","array_data:".json_encode($array_data)."\n\n",FILE_APPEND);
            $cbCode = $array_data["out_trade_no"];//取出回调码


//            取出自助升级信息
            $UserDiyLevelUpModel = new UserDiyLevelUpModel($this->getDoctrine());
            $Entity = $UserDiyLevelUpModel->getByCbCode($cbCode);
            $status = $Entity->getCbStatus();
            if ($status == 0) {
                //处理回调请求
                //todo 金额校验和合法性校验暂时不做
                $WechatPayModel = new WechatPayModel($this->getDoctrine());

                //间接升级
                $UserInviteExModel = new UserInviteExModel($this->getDoctrine());
                $userInvite = $UserInviteExModel->getUser($Entity->getTuid());

                //计算需要支付的金额
                $RulesModel = new RulesModel($this->getDoctrine());
                $Rule = $RulesModel->getByK("divide_vip");
                $moneyArray = $this->myExplodeNumbers($Rule->getV());
                $money = 0;
                $parentArray = $this->myExplodeNumbers($userInvite->getParent());
                $index = array_search($Entity->getUid(),$parentArray);
                $MoneyModel = new MoneyModel($this->getDoctrine());
                $UserModel = new UserModel($this->getDoctrine());
                $tUser = $UserModel->getUserById($Entity->getTuid());
                for ($i = 0;$i < $index;$i++) {
                    $money = $moneyArray[$i];
//                    检查父用户是否比目标用户等级高
                    $parent = $UserModel->getUserById($parentArray[$i]);
                    if ($tUser->getGroups() >= $parent->getGroups()) {
                        continue;
                    }


                    //为用户增加积分
                    $MoneyModel->addMoney($parentArray[$i],$money,BaseConfig::__STR_ADD_MONEY_FROM_LEVEL_UP__,"level");
                }
                $tUser->setGroups(5);
                $Entity->setCbStatus(1);
                $this->myEm()->persist($tUser);
                $this->myEm()->persist($Entity);
                $this->myEm()->flush();

                //更新用户限额数据
                $UserDiyLevelupLimitModel = new UserDiyLevelupLimitModel($this->getDoctrine());
                $UserDiyLevelupLimitModel->updateUserData($Entity->getUid());
            }

        }
        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';die;
    }



}
